package controller

import (
	"GoWeb/src/framework"
	"GoWeb/src/model"
	"GoWeb/src/service"
	"GoWeb/src/utils"
	"encoding/json"
	"fmt"
	"net/http"
)

/**
 * r.PostFormValue  : 可以解析 Post/PUT Content-Type=application/x-www-form-urlencoded 或 Content-Type=multipart/form-data
 */

type UserConterller struct {

}

var userService = new(service.UserService)

func (p *UserConterller) Router(router *framework.RouterHandler) {
	router.Router("/register", p.register)
	router.Router("/login", p.login)
	router.Router("/findAll", p.findAll)
	router.Router("/getName", p.findName)
	router.Router("/getUser", p.findNames)
}

//POST Content-Type=application/x-www-form-urlencoded
func (p *UserConterller) register(w http.ResponseWriter, r *http.Request) {
	username := r.PostFormValue("username")
	password := r.PostFormValue("password")
	if utils.Empty(username) || utils.Empty(password) {
		framework.ResultFail(w, "username or password can not be empty")
		return
	}
	users := userService.SelectUserByName(username)
	if len(users) != 0 {
		rs :=data(0,"用户已注册")
		framework.ResultFail(w,string(rs))
		return
	}

	id := userService.Insert(username, password)
	if id <= 0 {
		//framework.ResultFail(w, "register fail")
		rs :=data(0,"fail")
		framework.ResultFail(w,string(rs))
		return
	}
	rs :=data(1,"success")
	//"register success"
	framework.ResultOk(w, string(rs))
	//microcloud
}

func  data(code int,msg string) []byte {
	result := &model.ResultData{}
	result.Code = code
	result.Data=nil
	result.Msg=msg
	data, _ := json.Marshal(result)
	return data

}


//POST Content-Type=application/x-www-form-urlencoded
func (p *UserConterller) login(w http.ResponseWriter, r *http.Request) {
	username := r.PostFormValue("username")
	password := r.PostFormValue("password")
	if utils.Empty(username) || utils.Empty(password) {
		framework.ResultFail(w, "username or password can not be empty")
		return
	}
	users := userService.SelectUserByName(username)
	if len(users) == 0 {
		framework.ResultFail(w, "user does not exist")
		return
	}
	if users[0].Password != password {
		framework.ResultFail(w, "password error")
		return
	}

	framework.ResultOk(w, "login success")
}

// GET/POST
func (p *UserConterller) findAll(w http.ResponseWriter, r *http.Request) {
	users := userService.SelectAllUser()
	framework.ResultJsonOk(w, users)
}

func (p *UserConterller) findName(w http.ResponseWriter, r *http.Request) {
	query := r.URL.Query()
	username := query.Get("username")
	if utils.Empty(username) {
		framework.ResultFail(w, "username or password can not be empty")
		return
	}
	users := userService.SelectByName(username)
	framework.ResultJsonOk(w, users)

}
func (p *UserConterller) findNames(w http.ResponseWriter, r *http.Request) {
	username :=r.FormValue("username")
	fmt.Println(username)
	if utils.Empty(username) {
		framework.ResultFail(w, "username or password can not be empty")
		return
	}
	user := userService.SelectByNames(username)
	json, _ := json.Marshal(user)
	w.Write(json)
}